package com.junjiao.util.java.security;

public class SecurityHelper {
	public SecurityHelper() {
	}

	/**
	 * 简单口令加密函数
	 * 
	 * @Param original 明文
	 * @Return String 加密后的口令，长度为2*len(orgPass),前半部分为随机数
	 */
	public static String simplyEncrypt(String original) {
		String result = null;
		int len = original.length();
		byte rndArray[] = new byte[len];
		for (int i = 0; i < len; i++) {
			rndArray[i] = (byte) (32 + Math.random() * 50);
		}
		String key = new String(rndArray);
		byte orgArray[] = original.getBytes();
		byte enArray[] = new byte[len];
		for (int i = 0; i < len; i++) {
			int org = (int) orgArray[i];
			int rnd = (int) rndArray[i];
			enArray[i] = (byte) (org ^ rnd);
		}
		String enPass = new String(enArray);

		result = key + enPass;
		return result;
	}

	/**
	 * 简单解密函数，和simplyEncrypt函数相对应
	 * 
	 * @param original
	 *            String 密文
	 * @return String 明文
	 */
	public static String simplyDecrypt(String original) {
		String result = null;
		int len = original.length();
		int lenPass = len / 2;
		byte key[] = original.substring(0, lenPass).getBytes();
		byte enArray[] = original.substring(lenPass, len).getBytes();
		byte deArray[] = new byte[lenPass];
		for (int i = 0; i < lenPass; i++) {
			int org = (int) enArray[i];
			int rnd = (int) key[i];
			deArray[i] = (byte) (org ^ rnd);
		}

		result = new String(deArray);
		return result;
	}

	public static void main(String args[]) {
		SecurityHelper sh = new SecurityHelper();
		String original = "cctvjiaojun";
		String result = sh.simplyEncrypt(original);
		System.out.println("original = " + original);
		System.out.println("result = " + result);
		System.out.println(" dd " + sh.simplyDecrypt(result));
	}

}
